package tjs.study.mini.spingmvcmini.config.servlet;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractRefreshableConfigApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author nicky
 * @date 2021/9/7 下午2:17
 */
public class DispatcherServlet extends HttpServlet {

    private AbstractRefreshableConfigApplicationContext webApplicationContext;

    private RequestMappingHandlerAdapter mappingHandlerAdapter;

    public DispatcherServlet(AbstractRefreshableConfigApplicationContext webApplicationContext) {
        this.webApplicationContext = webApplicationContext;
    }

    @Override
    public final void init() throws ServletException {
        System.out.println("调用DispatcherServlet.init....");
        System.out.println("开始初始化IOC上下文....");
        webApplicationContext.refresh();// 初始化IOC上下文
        System.out.println("开始初始化mvc....");
        initStrategies(webApplicationContext);// 初始化mvc
    }

    protected void initStrategies(ApplicationContext context) {
        // 加载九大组件
        mappingHandlerAdapter = context.getBean(RequestMappingHandlerAdapter.class);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("请求: " + req.getRequestURI() + "进入....");
        Object result = mappingHandlerAdapter.invokeHandlerMethod(req, resp);

        System.out.println("请求: " + req.getRequestURI() + "结束，返回值为：" + JSONObject.toJSONString(result));
        writerResult(resp, result);
    }

    private void writerResult(HttpServletResponse resp, Object result) throws IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        resp.getWriter().println(JSONObject.toJSON(result));
        resp.getWriter().flush();
    }


}
